<?php
namespace app\appin\service;

use think\App;
use app\common\exception\AppinException;

class Package
{
    /**
     * [loadAppinPackageData 获取已经安装的插件的配置文件]
     * @return [type] [description]
     */
    public static function loader()
    {
        $appinPackagePath = app()->getRootPath() . '../appin/package.php';
        if ( !file_exists($appinPackagePath) ) {
            throw new AppinException('缺少package文件!');
        }
        $data = json_decode(
            str_replace(
                '<?php exit(); ?>',
                '',
                file_get_contents( $appinPackagePath )
            ), true
         );
         return !$data ? [] : $data;
    }

    /**
     * [load 加载package文件]
     * @param  string $appinName [description]
     * @return [type]            [description]
     */
    public static function load($appinName = '')
    {
        $package = static::loader();
        if ( empty($appinName) ) {
            return $package;
        }
        return isset($package[$appinName]) ? $package[$appinName] : false;
    }

    /**
     * 获取所有的安装的插件
     * [allAppin description]
     * @return [type] [description]
     */
    public static function allAppin()
    {
        $packages = static::load();
        if ($packages) {
            return array_keys( $packages );
        }
        return [];
    }

    /**
     * [install 安装一个应用]
     * @param  [type] $appName [description]
     * @return [type]          [description]
     */
    public static function install($appName)
    {
        $appConfPath = app()->getRootPath() . '../appin/'.$appName.'/app.php';
        $install[$appName] = include $appConfPath;
        $package = static::loader();
        return static::writer(array_merge($package, $install));
    }

    /**
     * [writer 将应用的配置写入文件]
     * @param  array  $data [description]
     * @return [type]       [description]
     */
    public static function writer(array $data)
    {
        $string = '<?php exit(); ?>'
        .json_encode($data, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);

        return file_put_contents(
            app()->getRootPath() . '../appin/package.php',
            $string
        );
    }
}
